package com.wbao.dianniu.ui;

import java.io.File;
import java.util.ArrayList;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadTask;
import com.alibaba.sdk.android.media.utils.FailReason;
import com.alibaba.sdk.android.media.utils.StringUtils;
import com.arlen.photo.photopickup.presenter.HeadPresenter;
import com.arlen.photo.photopickup.util.FileSizeUtil;
import com.bumptech.glide.Glide;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.TwoAuthDetailData;
import com.wbao.dianniu.listener.IIndustryAuthListener;
import com.wbao.dianniu.listener.ITwoAuthDetailListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.IndustryAuthManager;
import com.wbao.dianniu.manager.TwoAuthDetailManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 行业认证
 *
 * @author yejianjun
 */
public class IndustryAuthActivity extends BaseActivity implements IIndustryAuthListener, ITwoAuthDetailListener {

    private TwoAuthDetailManager dManger;
    private ImageView faceButton;
    private ImageView backButton;
    private ImageView otherButton;
    private Button submitBtn;
    private TextView seeSampleTV;
    private IndustryAuthManager manager;
    private String idBeforePic;
    private String idAfterPic;
    private String industryPic;
    private Dialog dialog;
    private Button photoBtn;
    private Button choosePicBtn;
    private Button cancel_dialog;
    private final int IMAGE_OPEN = 1; // 打开图片标记
    private int type;
    /**
     * 初始状态
     */
    private final int STATUS_INIT = 0;
    /**
     * 待审批
     */
    private final int STATUS_PENDING = 1;
    /**
     * 审批通过
     */
    private final int STATUS_PASS = 2;
    /**
     * 审批不通过
     */
    private final int STATUS_NO_PASS = 3;
    private int status = STATUS_INIT;
    private boolean isClick = false;
    private Integer Id = 0;
    private Dialog pDialog;
    private HeadPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_industry_auth, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        setTitleName(getResources().getString(R.string.industry_certification));
        initBaseView();
        manager = new IndustryAuthManager(this);
        manager.addIndustryAuthListener(this);
        dManger = new TwoAuthDetailManager(this);
        dManger.addTwoAuthDetailListener(this);
        dManger.twoAuthDetail(GlobalContext.getAccountId());
    }


    private void initBaseView() {
        faceButton = findViewById(R.id.imageButton_ID_face);
        backButton = findViewById(R.id.imageButton_ID_back);
        otherButton = findViewById(R.id.imageButton_other);
        submitBtn = findViewById(R.id.two_auth_submit);
        seeSampleTV = findViewById(R.id.see_sample);

        faceButton.setOnClickListener(this);
        backButton.setOnClickListener(this);
        otherButton.setOnClickListener(this);
        seeSampleTV.setOnClickListener(this);
        submitBtn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (TextUtils.isEmpty(idBeforePic)) {
                    Notification.toast(IndustryAuthActivity.this, "请上传身份证正面图");
                    return;
                } else if (TextUtils.isEmpty(idAfterPic)) {
                    Notification.toast(IndustryAuthActivity.this, "请上传身份证反面图");
                    return;
                } else if (TextUtils.isEmpty(industryPic)) {
                    Notification.toast(IndustryAuthActivity.this, "请上传行业截图");
                    return;
                }
                if (STATUS_INIT == status || STATUS_NO_PASS == status) {
                    if (!isClick) {
                        isClick = true;
                        manager.auth(Id, GlobalContext.getAccountId(), idBeforePic, idAfterPic, industryPic);
                    }
                } else {
                    Notification.toast(IndustryAuthActivity.this, "已经提交申请，不能重复提交");
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.imageButton_ID_face:  // 身份证正面
                if (STATUS_INIT == status || STATUS_NO_PASS == status) {
                    type = 1;
                    showRealase();
                } else if (STATUS_PENDING == status || STATUS_PASS == status) {
                    ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(idBeforePic);
                    imageBrower(0, imageUrls);
                }
                break;
            case R.id.imageButton_ID_back:  // 身份证反面
                if (STATUS_INIT == status || STATUS_NO_PASS == status) {
                    type = 2;
                    showRealase();
                } else if (STATUS_PENDING == status || STATUS_PASS == status) {
                    ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(idAfterPic);
                    imageBrower(0, imageUrls);
                }
                break;
            case R.id.imageButton_other:  //  行业认证截图
                if (STATUS_INIT == status || STATUS_NO_PASS == status) {
                    type = 3;
                    showRealase();
                } else if (STATUS_PENDING == status || STATUS_PASS == status) {
                    ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(industryPic);
                    imageBrower(0, imageUrls);
                }
                break;
            case R.id.btn_cancel:
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                break;
            case R.id.btn_take_photo:  // 拍照
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                //拍照
                PermissionUtils.getInstance().intentToCamera(this);
                break;
            case R.id.btn_pick_photo: //  选择图片
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                //选择图片
                PermissionUtils.getInstance().intentToPhoto(IndustryAuthActivity.this, IMAGE_OPEN, 1, null);
                break;
            case R.id.see_sample:
                Intent sampleIntent = new Intent();
                sampleIntent.setClass(IndustryAuthActivity.this, IndustrySampleActivity.class);
                startActivity(sampleIntent);
                overridePendingTransition(R.anim.zoom_enter, 0);
                break;
            /*case R.id.two_auth_submit:
                if (TextUtils.isEmpty(idBeforePic)) {
                    Notification.toast(IndustryAuthActivity.this, "请上传身份证正面图");
                    return;
                } else if (TextUtils.isEmpty(idAfterPic)) {
                    Notification.toast(IndustryAuthActivity.this, "请上传身份证反面图");
                    return;
                } else if (TextUtils.isEmpty(industryPic)) {
                    Notification.toast(IndustryAuthActivity.this, "请上传行业截图");
                    return;
                }
                if (STATUS_INIT == status || STATUS_NO_PASS == status) {
                    if (!isClick) {
                        isClick = true;
                        manager.auth(Id, GlobalContext.getAccountId(), idBeforePic, idAfterPic, industryPic);
                    }
                } else {
                    Notification.toast(this, "已经提交申请，不能重复提交");
                }
                break;*/

            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //打开图片
        if (resultCode == RESULT_OK && requestCode == IMAGE_OPEN) {
            Uri uri = data.getData();
            if (!TextUtils.isEmpty(uri.getAuthority())) {
                //查询选择图片  
                Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA},
                        null, null, null);
                //返回 没找到选择图片  
                if (null == cursor) {
                    return;
                }
                //光标移动至开头 获取图片路径
                cursor.moveToFirst();
                String pathImage = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();
                pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
                pDialog.setCancelable(false);
                pDialog.show();
                //图片选择成功，上传图片到cdn，得到cdn的路径
                String fileName = "image_" + StringUtils.getUUID();
                presenter = new HeadPresenter(IndustryAuthActivity.this);
                presenter.addUploadListener(new MyuploadLister(type, fileName, pathImage));
                presenter.uploadImageUrl(pathImage, fileName);
            }
        } else if (resultCode == RESULT_OK && requestCode == PermissionUtils.TAKE_PHOTO) {
            File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
            //图片选择成功，上传图片到cdn，得到cdn的路径
            String fileName = "image_" + StringUtils.getUUID();

            pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
            pDialog.setCancelable(false);
            pDialog.show();
            //图片选择成功，上传图片到cdn，得到cdn的路径
            presenter = new HeadPresenter(IndustryAuthActivity.this);
            presenter.addUploadListener(new MyuploadLister(type, fileName, picture.getPath()));
            presenter.uploadImageUrl(picture.getPath(), fileName);
        }

    }


    @Override
    public void onTwoAuthFailure(int errorCode, String errorMsg) {
        isClick = false;
    }

    @Override
    public void onTwoAuthSuccess() {
        Notification.toast(this, "上传成功");
        isClick = false;
        finish();
    }

    /**
     * 选择图片弹出框
     */
    private void showRealase() {
        dialog = new Dialog(this, R.style.custom_Dialog);
        try {
            Window win = dialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
            win.setWindowAnimations(R.style.buttom_animation);
        } catch (Exception e) {
            e.printStackTrace();
        }
        View view = LayoutInflater.from(this).inflate(R.layout.picture_select, null);
        photoBtn = view.findViewById(R.id.btn_take_photo);
        choosePicBtn = view.findViewById(R.id.btn_pick_photo);
        cancel_dialog = view.findViewById(R.id.btn_cancel);
        photoBtn.setOnClickListener(this);
        choosePicBtn.setOnClickListener(this);
        cancel_dialog.setOnClickListener(this);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
    }


    @Override
    public void onTwoAuthDetailFailure(int errorCode, String errorMsg) {
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onTwoAuthDetailSuccess(TwoAuthDetailData data) {
        if (null != data) {
            idBeforePic = data.getIdBeforePic();
            idAfterPic = data.getIdAfterPic();
            industryPic = data.getIndustryPic();
            status = data.getStatus();
            if (STATUS_PENDING == status) {
                submitBtn.setText("待审批");
                submitBtn.setClickable(false);
                submitBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
            } else if (STATUS_PASS == status) {
                GlobalContext.setIndustryAuthority(true);
                submitBtn.setText("审批通过");
                submitBtn.setClickable(false);
                submitBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
            } else if (STATUS_NO_PASS == status) {
                Id = data.getId();
                submitBtn.setText("审批不通过(点击重新上传)");
                submitBtn.setClickable(true);
            } else {
                submitBtn.setText("确认上传");
                submitBtn.setClickable(true);
            }
            if (null != idBeforePic) {
                showImage(idBeforePic, faceButton);
            }
            if (null != idAfterPic) {
                showImage(idAfterPic, backButton);
            }
            if (null != industryPic) {
                showImage(industryPic, otherButton);
            }

        }
    }

    private void showImage(String url, final ImageView image) {
        url = GlobalContext.cdndownUrl + url;
        Glide.with(this)
                .load(url)
                .into(image);
    }

    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(this, position, urls2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != manager) {
            manager.removeIndustryAuthListListener(this);
        }
        if (null != dManger) {
            dManger.removeTwoAuthDetailListListener(this);
        }
    }

    class MyuploadLister implements UploadListener {

        private int type;
        private String fileName;
        private String pathImage;

        public MyuploadLister(int type, String fileName, String pathImage) {
            this.type = type;
            this.fileName = fileName;
            this.pathImage = pathImage;
        }

        @Override
        public void onUploadCancelled(UploadTask uploadTask) {
            // TODO Auto-generated method stub
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }

        @Override
        public void onUploadComplete(UploadTask uploadTask) {
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            if (1 == type) {
                idBeforePic = fileName;
                Bitmap b = FileSizeUtil.compressBitmap(pathImage, faceButton.getWidth(), faceButton.getHeight());
                faceButton.setImageBitmap(b);
            } else if (2 == type) {
                idAfterPic = fileName;
                Bitmap b = FileSizeUtil.compressBitmap(pathImage, backButton.getWidth(), backButton.getHeight());
                backButton.setImageBitmap(b);
            } else if (3 == type) {
                industryPic = fileName;
                Bitmap b = FileSizeUtil.compressBitmap(pathImage, otherButton.getWidth(), otherButton.getHeight());
                otherButton.setImageBitmap(b);
            }
        }

        @Override
        public void onUploadFailed(UploadTask uploadTask, FailReason failReason) {
            // TODO Auto-generated method stub
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            Notification.toast(IndustryAuthActivity.this, "上传失败");
            UploadTask.Result result = uploadTask.getResult();
            String requestId = (null == result ? "null" : result.requestId);
//            Log.e("IndustryAuthActivity", "onUploadFailed:  " + " requestId:" + requestId + " code:" + failReason.getCode() + " reason:" + failReason.getMessage());
            if (1 == type) {
                idBeforePic = "";
                faceButton.setImageDrawable(getResources().getDrawable(R.drawable.two_auth_bg));
            } else if (2 == type) {
                idAfterPic = "";
                backButton.setImageDrawable(getResources().getDrawable(R.drawable.two_auth_bg));
            } else if (3 == type) {
                industryPic = "";
                otherButton.setImageDrawable(getResources().getDrawable(R.drawable.two_auth_bg));
            }
        }

        @Override
        public void onUploading(UploadTask uploadTask) {
            // TODO Auto-generated method stub
        }

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
